import React from 'react';
import { Table, Form, message, Switch, Button, Icon, Popconfirm, Upload } from 'antd';
import { connect } from 'dva';
import ModalC from 'components/Modal/dns/dns';
import moment from 'moment';


@connect(state => ({
  dns: state.dns,
}))
class Pages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      formatData: null,
      selectedRowKeys: [],
      type: 'add',
      currentId: null,
      switchLoading:false,
    };
  }

  //获取列表数据
  getList = (pageNum = 1, pageSize = 10) => {
    this.props.dispatch({
      type: 'dns/getList',
      payload: {
        pageNum,
        pageSize,
      },
    });
  };

  //提交数据
  submit = values => {
    const { type, currentId } = this.state;
    if (type === 'add') {
      this.props.dispatch({
        type: 'dns/add',
        payload: {
          ...values,
        },
        callback: () => {
          this.setState(
            {
              groupId: values.groupId,
            },
            () => this.getList()
          );
          this.closeModal();
        },
      });
    } else {
      this.props.dispatch({
        type: 'dns/edit',
        payload: {
          ...values,
          id: currentId,
        },
        callback: () => {
          this.getList();
          this.closeModal();
        },
      });
    }
  };

  /**
   * 删除
   */
  delete = ids => {
    this.props.dispatch({
      type: 'dns/delete',
      payload: {
        ids,
      },
      callback: () => {
        this.setState({
          selectedRowKeys: [],
        });
        this.getList();
      },
    });
  };
  deleteAll = () => {
    const { selectedRowKeys } = this.state;
    this.delete(selectedRowKeys);
  };
  //批量删除
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  /**
   * modal
   */
  closeModal = () => {
    this.setState({
      visible: false,
      formatData: null,
    });
  };
  //新增编辑
  updateBtn = (type = 'add', record = null) => {
    if (type === 'add') {
      this.setState({
        type: 'add',
        visible: true,
      });
    } else {
      this.setState({
        type: 'edit',
        currentId: record.id,
        visible: true,
        formatData: record,
      });
    }
  };

  /**
   * 刷新

   */
  freshDns = () => {
    this.props.dispatch({
      type: 'dns/freshDns',
      payload: {},
    });
  };

  /**
   * 导入
   */
  upload = data => {
    if (data.file.status === 'done') {
      if (data.file.response.code === 200) {
        message.info('导入成功');
        this.getList();
      } else {
        message.error(data.file.response.msg);
      }
    }
  };

    /**
   * 开启关闭域名
   */
  handleSwitch = value => {
    this.setState({
      currentId: value.id,
      switchLoading: true,
    });
    this.props.dispatch({
      type: 'dns/edit',
      payload: {
        id: value.id,
        openState: value.openState === 0 ? 1 : 0,
      },
      callback: (pageNum, pageSize) => {
        this.getList(pageNum, pageSize);
        this.setState({
          currentId: null,
          switchLoading: false,
        });
      },
    });
  };

  componentDidMount() {
    this.getList();
  }

  render() {
    const {
      dns: { list, loading },
    } = this.props;
    const { visible, formatData, selectedRowKeys,switchLoading,currentId } = this.state;

    const colomns = [
      {
        title: '域名',
        dataIndex: 'domain',
        width: 100,
      },
      {
        title: '状态',
        dataIndex: 'openState',
        width: 100,
        render: (text, record) => (
          <Switch
            loading={switchLoading && currentId === record.id}
            onChange={() => this.handleSwitch(record)}
            checked={text === 1}
            checkedChildren="开"
            unCheckedChildren="关"
          />
        ),
      },
      {
        title: '记录值',
        dataIndex: 'recordValue',
        width: 100,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        width: 100,
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        width: 100,
        render: text => <span>{moment(text).format('YYYY年MM月DD日')}</span>,
      },
      {
        title: '更新时间',
        dataIndex: 'updateDate',
        width: 100,
        render: text => <span>{moment(text).format('YYYY年MM月DD日')}</span>,
      },
      {
        title: '操作',
        width: 80,
        render: (text, record) => (
          <>
            <span onClick={() => this.updateBtn('edit', record)} className="btnG">
              编辑
            </span>
          </>
        ),
      },
    ];

    const rowSelection = {
      columnWidth: 10,
      onChange: this.onSelectChange,
    };

    return (
      <>
        <h3 className="head">域名解析</h3>
        <div style={{ padding: '10px 20px' }}>
          {selectedRowKeys.length > 0 && (
            <Popconfirm
              title="确定要删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => this.deleteAll()}
            >
              <Button
                // style={{ marginTop: '20px' }}
                type="primary"
                disabled={selectedRowKeys <= 0}
                icon="delete"
              >
                批量删除
              </Button>
            </Popconfirm>
          )}
          <Popconfirm
            title="确定要启用配置吗？"
            okText="确定"
            cancelText="取消"
            onConfirm={() => this.freshDns()}
          >
            <Button className="ml10" type="primary" icon="tool">
              启用配置
            </Button>
          </Popconfirm>
          <Upload             headers={{
              accessToken: localStorage.getItem('tokenId'),
            }} action="/api/api/v1/redirect/importExcel" onChange={this.upload} showUploadList={false}>
            <Button className="ml10" type="primary" icon="import">
              导入
            </Button>
          </Upload>

          <Table
            rowKey="id"
            style={{ marginBottom: '50px' }}
            loading={loading}
            columns={colomns}
            dataSource={list}
            rowSelection={rowSelection}
            pagination={false}
          />
          <Button type="primary" onClick={() => this.updateBtn()}>
            新增域名
          </Button>

          <ModalC
            list={list}
            visible={visible}
            close={this.closeModal}
            formatData={formatData}
            submit={this.submit}
          />
        </div>
      </>
    );
  }
}

export default Pages;
